from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器类"""
    sku_id = serializers.IntegerField(label='商品id')
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='勾选状态', default=True)

    def validate(self, attrs):
        '''
        校验参数
        1. 商品是否存在
        2. 商品库存是否足够
        '''
        # 1. 商品是否存在
        sku_id = attrs['sku_id']
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 2. 商品库存是否足够

        count = attrs['count']
        if count > sku.stock:
            raise serializers.ValidationError('商品数量不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    '''购物车商品的序列化器类'''
    count = serializers.IntegerField(label='商品数量')
    selected = serializers.BooleanField(label='勾选状态')

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'count', 'selected')



class CartDelSerializer(serializers.Serializer):
    '''购物车删除商品'''
    sku_id = serializers.IntegerField(label='商品id', min_value=1)


    def validate_sku_id(self, value):
        '''校验商品是否存在'''
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoseNotExist:
            raise serializers.ValidationError('商品不存在')

        return value


class CartSelectedSerializer(serializers.Serializer):
    '''用户购物车全选与取消全选序列化器类'''
    selected = serializers.BooleanField(label='勾选状态')
